package com.agileai.crm.module.customer.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.agileai.crm.common.PrivilegeHelper;
import com.agileai.crm.cxmodule.CustomerGroup8ContentManage;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.controller.core.TreeAndContentManageListHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.ListUtil;

public class CustomerSale8ContentListHandler
        extends TreeAndContentManageListHandler {
		protected Class<CustomerInfoEditHandler> editHandlerClazz = null;
		protected String nodeIdField = "CUST_ID";
		protected String nodePIdField = "GRP_SUP_ID";
    public CustomerSale8ContentListHandler() {
        super();
        this.serviceId = buildServiceId(CustomerGroup8ContentManage.class);
        this.rootColumnId = "00000000-0000-0000-00000000000000000";
        this.defaultTabId = "CustomerInfo";
        this.columnIdField = "USER_ID";
        this.columnNameField = "USER_NAME";
        this.columnParentIdField = "USER_SUP_ID";
        this.editHandlerClazz = CustomerInfoEditHandler.class;
    }
    
    public ViewRenderer prepareDisplay(DataParam param){
    	User user = (User) this.getUser();
		PrivilegeHelper privilegeHelper = new PrivilegeHelper(user);
		if (!privilegeHelper.isSalesDirector()) {
			param.put("currentUserCode", user.getUserId());
		} else {
			param.put("currentUserCode", "");
		}
		setAttribute("hasRight", true);
		initParameters(param);
		this.setAttributes(param);
		String columnId = param.get("columnId",this.rootColumnId);
		this.setAttribute("columnId", columnId);
		this.setAttribute("isRootColumnId",String.valueOf(this.rootColumnId.equals(columnId)));
		
		TreeBuilder treeBuilder = provideTreeBuilder(param);
		TreeModel treeModel = treeBuilder.buildTreeModel();
		TreeModel filterTreeModel = null;
		TreeModel childModel = treeModel.getChildrenMap().get(columnId);
		if (childModel != null){
			filterTreeModel = childModel;
		}else{
			filterTreeModel = treeModel;
		}
		
		String menuTreeSyntax = this.getTreeSyntax(treeModel,new StringBuffer());
		this.setAttribute("menuTreeSyntax", menuTreeSyntax);
		String tabId = param.get(TreeAndContentManage.TAB_ID,this.defaultTabId);

		String custState = param.get("custState");
		String custStates = "";
		if(custState != null){
			String state[] = custState.split(",");
			for(int i=0;i<state.length;i++){
				String custStateTemp = state[i];
				if(i == 0){
					custStates = "'"+custStateTemp+"'";
				}else{
					custStates = custStates +","+"'"+custStateTemp+"'";
				}
			}
		}
		param.put("custStates", custStates);
		
		String custLevel = param.get("custLevel");
		String custLevels = "";
		if(custLevel != null){
			String level[] = custLevel.split(",");
			for(int i=0;i<level.length;i++){
				String custLevelTemp = level[i];
				if(i == 0){
					custLevels = "'"+custLevelTemp+"'";
				}else{
					custLevels = custLevels +","+"'"+custLevelTemp+"'";
				}
			}
		}
		param.put("custLevels", custLevels);
	
		
		if (!TreeAndContentManage.BASE_TAB_ID.equals(tabId)){
			param.put("columnId",columnId);
			List<DataRow> rsList = getService().findContentRecords(filterTreeModel,tabId,param);
			this.setRsList(rsList);			
		}else{
			DataParam queryParam = new DataParam(columnIdField,columnId);
			DataRow row = getService().queryTreeRecord(queryParam);
			this.setAttributes(row);
		}
		
		this.setAttribute(TreeAndContentManage.TAB_ID, tabId);
		this.setAttribute(TreeAndContentManage.TAB_INDEX, getTabIndex(tabId));
		
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}

    protected void processPageAttributes(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("CustomerInfo".equals(tabId)) {
            setAttribute("custState",
                         FormSelectFactory.create("CUST_STATE")
                                          .addSelectedValue(param.get("custState")));
            setAttribute("custIndustry",
                    FormSelectFactory.create("CUST_INDUSTRY")
                                     .addSelectedValue(param.get("custIndustry")));
            setAttribute("custScale",
                    FormSelectFactory.create("CUST_SCALE")
                                     .addSelectedValue(param.get("custScale")));
            setAttribute("custLevel",
                    FormSelectFactory.create("CUST_LEVEL")
                                     .addSelectedValue(param.get("custLevel")));
            setAttribute("custCity", FormSelectFactory.create("cityRecord", param)
    				.addSelectedValue(getOperaAttributeValue("custCity", "")));
            
            initMappingItem("CUST_INDUSTRY",
                            FormSelectFactory.create("CUST_INDUSTRY")
                                             .getContent());
            initMappingItem("CUST_SCALE",
                            FormSelectFactory.create("CUST_SCALE").getContent());
            initMappingItem("CUST_LEVEL",
                            FormSelectFactory.create("CUST_LEVEL").getContent());
            initMappingItem("CUST_STATE",
                            FormSelectFactory.create("CUST_STATE").getContent());
            initMappingItem("CUST_CITY",
                    FormSelectFactory.create("CUST_CITY").getContent());
        }
    }

    protected void initParameters(DataParam param) {
        String tabId = param.get(TreeAndContentManage.TAB_ID, this.defaultTabId);

        if ("CustomerInfo".equals(tabId)) {
          
        }
    }
    
	@PageAction
	public ViewRenderer refreshCitySelect(DataParam param){
		String responseText = FAIL;
		String custProvince = param.get("CUST_PROVINCE");
		List<DataRow> records = getService().findCityRecords(custProvince);
		FormSelect formSelect = new FormSelect();
		formSelect.setKeyColumnName("CITY_ID");
		formSelect.setValueColumnName("CITY_NAME");
		formSelect.putValues(records);
		
		responseText = formSelect.getSyntax();
		
		return new AjaxRenderer(responseText);
	}

    protected TreeBuilder provideTreeBuilder(DataParam param) {
        CustomerGroup8ContentManage service = this.getService();
        List<DataRow> menuRecords = service.findSaleTreeRecords(param);
        TreeBuilder treeBuilder = new TreeBuilder(menuRecords,
                                                  this.columnIdField,
                                                  this.columnNameField,
                                                  this.columnParentIdField);
        return treeBuilder;
    }

    protected List<String> getTabList() {
        List<String> result = new ArrayList<String>();
        result.add("CustomerInfo");

        return result;
    }
    
    public ViewRenderer doDeleteAction(DataParam param){
		DataParam dataParam = new DataParam("CUST_ID",param.get("CUST_ID"));
		List<DataRow> personRecords = getService().findPersonRecords(dataParam);
		if (!ListUtil.isNullOrEmpty(personRecords)){
			this.setErrorMsg("存在联系人信息,不能删除!");
			return prepareDisplay(param);
		}
		DataParam dataParam1 = new DataParam("custId",param.get("CUST_ID"));
		List<DataRow> salesRecords = getService().findSalesRecords(dataParam1);
		if (!ListUtil.isNullOrEmpty(salesRecords)){
			this.setErrorMsg("存在关联销售信息,不能删除!");
			return prepareDisplay(param);
		}
		DataRow sales = getService().getStatisticsRecords(dataParam1);
		int visitNum = Integer.parseInt(sales.stringValue("STATIS_VISIT"));
		int oppNum = Integer.parseInt(sales.stringValue("STATIS_OPP"));
		int orderNum = Integer.parseInt(sales.stringValue("STATIS_ORDER"));
		
		if (visitNum > 0 || oppNum > 0 || orderNum > 0 ){
			this.setErrorMsg("该客户已被引用,不能删除!");
			return prepareDisplay(param);
		}
		
		TreeAndContentManage service = this.getService();
		String tabId = param.get(TreeAndContentManage.TAB_ID);
		String columnId = param.get("curColumnId");
		Map<String,String> tabIdAndColFieldMapping = service.getTabIdAndColFieldMapping();
		String colField = tabIdAndColFieldMapping.get(tabId);
		param.put(colField,columnId);
		service.deletContentRecord(tabId,param);	
		return prepareDisplay(param);
	}
    
    @PageAction
    public ViewRenderer mergeRecord(DataParam param){
    	String responseText = "";
    	String custId = param.get("custId");
    	String targetId = param.get("targetId");
    	
    	getService().updateStateInfoRecord(new DataParam("CUST_ID",custId,"CUST_STATE","Postpone"));
    	//查询拜访记录
    	List<DataRow> rsList = getService().findCustVisitInfoRecords(new DataParam("VISIT_CUST_ID",custId));
    	//更新关联拜访记录关联客户ID
    	for(int i=0;i<rsList.size();i++){
    		DataRow dataRow = rsList.get(i);
    		String visitId = dataRow.getString("VISIT_ID");
    		getService().updateVisitCustIdRecord(new DataParam("VISIT_ID",visitId,"VISIT_CUST_ID",targetId));
    	}
    	
    	responseText = SUCCESS;
		return new AjaxRenderer(responseText);
    }
    
	public ViewRenderer doMoveContentAction(DataParam param){
		String rspText = SUCCESS;
		String ids = param.get("ids");
    	String[] idArray = ids.split(",");
		String saleUserId = param.get("targetParentId");
    	for(int i=0;i<idArray.length;i++){
    		String custId = idArray[i];
    		List<DataRow> rsList = getService().findSalesManRelation(new DataParam("CUST_ID",custId));
    		for(int j=0;j<rsList.size();j++){
    			DataRow dataRow = rsList.get(j);
    			String userId = dataRow.getString("USER_ID");
    			getService().delUserTreeRelation(custId, userId);
    		}
    		getService().addSalesManRelation(new DataParam("custId",custId,"userId",saleUserId));
    	}
    	
		return new AjaxRenderer(rspText);
	}
    
	public ViewRenderer doDeleteSaleRelationAction(DataParam param){
		String ids = param.get("ids");
    	String[] idArray = ids.split(",");
    	String userId = param.get("columnId");
    	for(int i=0;i<idArray.length;i++){
    		String custId = idArray[i];
    		getService().delUserTreeRelation(custId, userId);
    	}
		return prepareDisplay(param);
	}

    protected CustomerGroup8ContentManage getService() {
        return (CustomerGroup8ContentManage) this.lookupService(this.getServiceId());
    }
}
